package com.dengke.springmybatis.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import com.dengke.springmybatis.pojo.City;
import com.dengke.springmybatis.pojo.CityInfo;
import com.dengke.springmybatis.pojo.Country;
import com.dengke.springmybatis.service.CityService;
import com.dengke.springmybatis.service.CountryService;

@Controller
public class CityController {

	@Autowired
	private CityService cityService;

	@Autowired
	private CountryService countryService;
	@RequestMapping("/city")
	public String city(Model model) {
		City city = this.cityService.getCity(1);
		model.addAttribute("city", city);
		List<String>countryCodes=cityService.selectCountryCode();
		model.addAttribute("codes", countryCodes);
//		List<Country>countries= countryService.selectCityOfCountry();
//		for (Country item : countries) {
//			System.out.println(item);
//		}
		return "addcity";
	}
	
	@RequestMapping(value="/city",method=RequestMethod.POST)
	public String city(City city) {
		System.out.println("update city.....");
		this.cityService.updateCity(city);
		return "redirect:/citylist";
	}
	@RequestMapping("/")
	public String home(Model model) {
		model.addAttribute("home", "This is home page!");
		//在此处添加测试方法
//		CityInfo info= cityService.GetCityInfoById(1);
//		System.out.println(info.toString());
//		City city=cityService.GetCityById(1);
//		System.out.println(city);
		return "home";
	}
	@RequestMapping("/citylist")
	public String citylist(Model model){
		List<City>lists=this.cityService.getTop100City();
		model.addAttribute("cities", lists);
		return "citylist";
	}
	
	@GetMapping("/cityjson")
	@ResponseBody
	public Object citylist4json() {
		return this.cityService.getTop100City();
	}
	
	@RequestMapping(value= "/addcity",method=RequestMethod.GET)
	public String addcity(Model model) {
		//get country code ,in the city table the code is fk.
		List<String>countryCodes=cityService.selectCountryCode();
		model.addAttribute("codes", countryCodes);
		return "addcity";
	}
	
	@RequestMapping(value="/addcity",method=RequestMethod.POST)
	public String savecity(City city){
		System.out.println(city.toString());
		this.cityService.insert(city);
		return "redirect:/citylist";
	}
}
